from odoo import fields, models, api


class ProducctTemplate(models.Model):
    _inherit = 'product.template'

    s_base_id = fields.Many2one('s.product.base', 'base product', copy=False, tracking=True)

    s_is_finished = fields.Boolean(compute='_compute_s_is_finished')
    # 禁止下卡
    s_disable_down_card = fields.Boolean(string='禁止下卡', tracking=True, default=True)
    # 禁止下单
    s_disable_order = fields.Boolean(string='禁止下单', tracking=True)
    # 禁止过数
    s_disable_workorder = fields.Boolean(string='禁止过数', tracking=True)
    # 禁止出货
    s_disable_delivery = fields.Boolean(string='禁止出货', tracking=True)

    @api.model_create_multi
    def create(self, vals_list):
        result = super().create(vals_list)
        for rec in result:
            dtl = {}
            if rec.s_is_finished:
                dtl.update({
                    's_disable_down_card': True,
                    's_disable_order': True,
                })
            if rec.tracking in ('lot', 'serial') and not rec.use_expiration_date:
                if not rec.categ_id.s_use_expiration_date and not rec.categ_id.parent_id.s_use_expiration_date:
                    continue
                category = rec.categ_id if rec.categ_id.s_use_expiration_date else rec.categ_id.parent_id
                dtl.update({
                    'use_expiration_date': category.s_use_expiration_date,
                    'expiration_time': category.s_expiration_time,
                    'use_time': category.s_use_time,
                    'removal_time': category.s_removal_time,
                    'alert_time': category.s_alert_time,
                })
            if dtl:
                rec.write(dtl)
        return result

    @api.depends('categ_id')
    def _compute_s_is_finished(self):
        for rec in self:
            if rec.categ_id.name in ['Finished product', '成品', 'Semi Product', '半成品', '受托加工', 'Consigned Processing']:
                rec.s_is_finished = True
            else:
                rec.s_is_finished = False

    @api.constrains('serial_number', 'versions')
    def constrains_serial_number(self):
        for rec in self:
            if rec.s_base_id:
                continue
            if rec.categ_id.code and rec.categ_id.code == 'CHP' and rec.serial_number and rec.versions:  # 仅限成品
                version_char = rec.versions[0] if rec.versions else ''
                base_product_name = f'{rec.serial_number}-{version_char}'
                base_product_id = self.env['s.product.base'].search([('name', '=', base_product_name)], limit=1)
                if not base_product_id:
                    base_product_id = self.env['s.product.base'].create({'name': base_product_name})
                rec.write({'s_base_id': base_product_id.id})